/*
 * vfd.c
 *
 * Created: 15.01.2014 4:03:41
 *  Author: Vladislav
 */ 
#include "vfd.h"
#include "includes.h"


// table for translate ansii russian symbol in VFD russian symbol
const char __flash Transl[32]={0x41,0x80,0x42,0x81,0x82,0x45,0x83,0x84,
	0x85,0x86,0x4b,0x87,0x4d,0x48,0x4f,0x88,
	0x50,0x43,0x54,0x89,0x8a,0x58,0x8b,0x8c,
0x8d,0x8e,0x8f,0x90,0x62,0x91,0x92,0x93};




void VFD_CH (unsigned char comm);
void translate(char* Str);

int usartvfd_putchar(char c, FILE *stream);
FILE mystdout_vfd = FDEV_SETUP_STREAM(usartvfd_putchar, NULL, _FDEV_SETUP_WRITE);

void vfd_clear(void)
{
	//char str[20];
	//memset(str,0,20);
	//DisplayMsg(0,str);
	//DisplayMsg(20,str);
	//DisplayMsg(40,str);
	//DisplayMsg(60,str);
	VFD_CH(0xe);
	OSTimeDlyHMSM(0,0,0,6);
	
}


void VFD_CH (unsigned char comm) // one char on VFD immediate
{
	while ((USARTE0.STATUS & 0x20) == 0) {}; //USARTF0.STATUS.DREIF_bm
	USARTE0.DATA=comm;
}

void VfdInit (void)
{
	//USARTEinit ();  // VFD (19.2Kbod, even)
	stdout=&mystdout_vfd;
	PORTE_DIRCLR=1; // (28) busy from VFD
	PORTE_OUTSET=2; // reset VFD
	PORTE_DIRSET=2; // (29) reset VFD

	PORTE_OUTCLR=2; // hard initialise VFD (reset-not active)
	PORTA_OUTSET=0x10; // signal "upr" = 1;
	PORTA_DIRSET=0x11; // USART transmitter unlock (44), latch (40)
	// soft initialise VFD
	VFD_CH(0x1b);
	OSTimeDlyHMSM(0,0,0,10);
	
	VFD_CH(0x49); // soft initialise VFD
	OSTimeDlyHMSM(0,0,0,10);
	//VFD_CH(0x15); // cursor on
	
	//OSTimeDlyHMSM(0,0,0,10);
	VFD_CH(0x19); // katakana font
	OSTimeDlyHMSM(0,0,0,10);
}


int usartvfd_putchar(char c, FILE *stream)
{
	if (c == '\n')
	usartvfd_putchar('\r', stream);
	// Wait for the transmit buffer to be empty
	while (!( USARTE0.STATUS & USART_DREIF_bm));
	// Put our character into the transmit buffer
	USARTE0.DATA = c;
	return 0;
}

void translate(char* Str)
{
	uint8_t i=0, j;
	int len = strlen(Str);
	
	for(i=0;i<len;i++)
	{
		j=Str[i];
		if (j>=0xc0)
		j=Transl[j&0x1f];
		
		Str[i] = j;
	}
	
}



void DisplayArrows(uint8_t pos)
{
	if(pos!=CUR_POS)
	vfd_pos(pos);
	//OSTimeDlyHMSM(0,0,0,6);
	VFD_CH(0xFC);
	VFD_CH(0xFA);
	//OSTimeDlyHMSM(0,0,0,10);
}

void DisplayMsg(uint8_t pos,char* msg)
{
	//char str[20];
	//memcpy(&str[0],msg,20);
	if(pos!=CUR_POS)
	vfd_pos(pos);
	//OSTimeDlyHMSM(0,0,0,6);
	translate(msg);
	printf(msg);
	//OSTimeDlyHMSM(0,0,0,6);
}

 void vfd_pos(uint8_t pos)
 {
	 usartvfd_putchar(0x1b,(FILE*)&stdout);
	 usartvfd_putchar(0x48,(FILE*)&stdout);
	 usartvfd_putchar(pos,(FILE*)&stdout);
	 
 }